package com.bw.interceptor;

import com.alibaba.fastjson.JSON;
import com.bw.commpn.JwtUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class LoginInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 从当前电脑的内存里查询用户
//        Object user = request.getSession().getAttribute("user");
//        if (user == null){
//            response.sendRedirect("/loginPage.do");
//            return false;
//        }

        // 默认拦截所有人
        boolean b = false;
        // 从request中 解析出  浏览器发过来的cookie
        Cookie[] cookies = request.getCookies();
        System.out.println("拦截器 打印  浏览器发过来的cookie " + JSON.toJSONString(cookies));

        if (cookies != null) {

            for (Cookie cookie : cookies) {
                String name = cookie.getName();
                if (name.equals("token")) {  // 过滤cookie  从cookie中找到令牌 token

                    String token = cookie.getValue();

                    b = JwtUtils.validToken(token);  // 验证令牌是否有效
                }
            }
        }

        if (b == false) {
            response.sendRedirect("/loginPage.do");
            return false;
        }


        // 继续执行 下一个拦截器  执行链
        return HandlerInterceptor.super.preHandle(request, response, handler);
    }
}
